package me.zhengjie.modules.weixin.analyzer;

import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.modules.weixin.analyzer.impl.DefaultAnalyzer;
import me.zhengjie.modules.weixin.dto.WeChatAccount;
import me.zhengjie.modules.weixin.dto.WeChatMessage;
import me.zhengjie.modules.weixin.enums.WeChatMsgTypeEnum;
import me.zhengjie.modules.weixin.message.AnalyzerReplyMessage;
import me.zhengjie.modules.weixin.utils.ClazzUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 解析消息工厂类
 */
@Component
public class AnalyzerFactory {


    public WeChatMessage analyze(WeChatAccount account, Map<String, Object> receiveMsg) throws Exception {

        String msgType = (String) receiveMsg.get("MsgType");
        String openId = (String) receiveMsg.get("FromUserName");

        AbstractAnalyzer analyzer = null;
        try {
            Class<?> clazz = ClazzUtil.INSTANCE.getAnalyzer(msgType);
            if (null != clazz) {
                Constructor<?> constructor = clazz.getConstructor(WeChatAccount.class, Map.class);
                analyzer = (AbstractAnalyzer) constructor.newInstance(account, receiveMsg);
            }
        } catch (WeChatException e) {
            analyzer = new DefaultAnalyzer(account, receiveMsg);
        }

        if (null == analyzer) {
            analyzer = new DefaultAnalyzer(account, receiveMsg);
        }

        WeChatMessage weChatMessage = analyzer.analyze();
        if (null == weChatMessage) {
            weChatMessage = new WeChatMessage();
            weChatMessage.setMsgType(WeChatMsgTypeEnum.text.name());
        }

        List<AnalyzerReplyMessage> replies = weChatMessage.getReplyMessage();
        if (CollectionUtils.isEmpty(replies)) {
            // 默认的回复处理
            replies = new ArrayList<>();
            AnalyzerReplyMessage defaultReply = new AnalyzerReplyMessage();
            defaultReply.setModule("Default");
            defaultReply.setRule("-1");
            defaultReply.setReceiveMsg(receiveMsg);
            defaultReply.setPriority(Integer.MAX_VALUE);
            defaultReply.setReplyType(WeChatMsgTypeEnum.text.name());
            replies.add(defaultReply);

            weChatMessage.setReplyMessage(replies);
        }

        return weChatMessage;
    }

}
